﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lapkin.Attributes;
using Lapkin.Models.DataModels;
using Lapkin.Models.Repositories;

namespace Lapkin.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class VariantController : Controller
    {
        private readonly SqlRepository _repository = new SqlRepository();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost, IsAjax]
        public JsonResult ListVariant()
        {
            IEnumerable<ProductVariant> variants = _repository.ProductRepository.GetListProductVariant();
            var fVariants =
                from p in variants
                select new
                {
                    Id = p.Id,
                    Name = p.Name
                };
            return Json(new { Result = "OK", Records = fVariants });
        }

        [HttpPost, IsAjax]
        public JsonResult AddVariant(ProductVariant variant)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
            }

            ProductVariant productProperty = _repository.ProductRepository.CreateProductVariant(p => p.Name = variant.Name);
            return productProperty != null ?
                Json(new { Result = "OK", Record = productProperty }) :
                Json(new { Result = "ERROR", Message = "Error" });
        }

        [HttpPost, IsAjax]
        public JsonResult UpdateVariant(ProductVariant variant)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
            }
            _repository.ProductRepository.UpdateProductVariant(variant);
            return Json(new { Result = "OK" });
        }

        [HttpPost, IsAjax]
        public JsonResult RemoveVariant(ProductVariant variant)
        {
            if (!_repository.ProductRepository.RemoveProductVariant(variant.Id))
            {
                return Json(new { Result = "ERROR", Message = "Error_delete" });
            }
            return Json(new { Result = "OK" });
        }
    }
}
